package com.cunyu.util;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import org.apache.commons.lang.math.RandomUtils;

import cn.tom.kit.cache.TimedCache;

public class VcodeUtil {
	public static TimedCache<String, Object> timedCache = new TimedCache<String, Object>(30* 60000);
	
	/**
	 * 发送验证码
	 * @param tel
	 * @return
	 */
	public static boolean sendcode(String tel, String pname){
		String code = ""+code();;
		if(send(tel, code, pname)==1){
			set(tel, code, 10 * 60);
			return true;
		}
		return false;
	}
	
	public static void set(String tel, String code, int second){
		timedCache.put(tel, code, second *1000);
	}
	
	public static String get(String tel){
		return (String)timedCache.get(tel);
	}
	
	public static void del(String tel){
		timedCache.remove(tel);
	}
	
	/**
	 * 检查验证码
	 * @param tel
	 * @param code
	 * @return
	 */
	public static boolean checkcode(String tel, String code){
		if(code.equals(get(tel))){
			del(tel);
			return true;
		}
		return false;
	}
	
	/**
	 * @deprecated
	 * @param token
	 * @return
	 */
	public static boolean checktoken(String token){
		if("1".equals(get(token))){
			del(token);
			return true;
		}
		return false;
	}

	public static int code() {
		int code = RandomUtils.nextInt(9999);
		if (code > 999)
			return code;
		return code();
	}
	
	/**
	 * 容联云短信发送
	 * @param mobile
	 * @param content
	 * @param code
	 * @return app.cloopen.com:8883
	 */
	public static int send(String mobile, String code,String pname) {
		String url ="http://smssh1.253.com/msg/send/json";
		HashMap<String, String> params = new HashMap<>();
		params.put("account", "N5247022");
		params.put("password", "s251keaJXVc8ab");
		params.put("msg", "【"+pname+"】您的短信验证码为"+code+", 若非本人操作请忽略。");
		params.put("phone", mobile);
		String str = HttpUtil.postJson(url, "UTF-8", params);
		System.out.println("code==>" + code +" ==resp=="+str);
		if(str.indexOf("\"code\":\"0\"")!=-1){
			return 1;
		}
		return 0;
	}
	
	public static int notice(String mobile,String msg) {
		String url ="http://smssh1.253.com/msg/send/json";
		HashMap<String, String> params = new HashMap<>();
		params.put("account", "N5247022");
		params.put("password", "s251keaJXVc8ab");
		params.put("msg", msg);
		params.put("phone", mobile);
		String str = HttpUtil.postJson(url, "UTF-8", params);
		System.out.println("==notice=="+str);
		if(str.indexOf("\"code\":\"0\"")!=-1){
			return 1;
		}
		return 0;
	}
	
	
	public void setToken(String code){
		VcodeUtil.set(code, "1", 60);
	}
	
	public boolean checkToken(String token, String code){
		if("1".equals(VcodeUtil.get(code))){
			return true;
		}
		return false;
	}
	
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		
//		System.out.println(send("13775237258", "122223", "无需等贷"));
//		【"+msgTag+"】"+name+", 您的物流已在路上外发单号为: "+uvlimit
		System.out.println(notice("13775237258", "【无需等贷】[猪八戒]您的物流已在路上外发单号为:200"));
	}


}
